# coding: utf8

from ops.chatbot.utils.send_msg import SendMessage
from ops.chatbot.utils.utils import split_project
from ops.chatbot.cmds.get_project import get_projects
import requests
from urllib.parse import urljoin
from ops.devops.utils.util_config import get_config


# deploy命令时执行如下函数
def deploy(*args, **kwargs):
    webhook = kwargs.get("webhook")

    # 支持输入多个并去重
    project_list = list(set(args))
    msg_list = []
    for project_origin in project_list:
        # 以-分割传入的参数project_origin
        alias_name, tag_or_branch, deploy_env = split_project(project_origin)

        all_projects = get_projects()

        # alias_name==help时，返回帮助并跳过本次循环
        if alias_name == 'help':
            for k, v in all_projects.items():
                tmp = '发布项目%s：deploy %s-tag-env\n' % (v, k)
                msg_list.append(tmp)
            continue

        # tag为空或tag不符合则跳出循环
        if not tag_or_branch or deploy_env not in ['pre', 'prod']:
            msg = {"errCode": 404, "msg": "未获取到项目:%s的tag或tag不正确，当前project_tag_env=%s!\n" % (alias_name, project_origin)}
            msg_list.append(msg.get('msg'))
            continue

        # 未获取到配置则跳过本次循环
        if alias_name not in all_projects.keys():
            msg = {"errCode": 404, "msg": "项目:%s不存在，请用deploy help获取命令!\n" % alias_name}
            msg_list.append(msg.get('msg'))
            continue

        data = {
                "alias_name": alias_name,
                "version": tag_or_branch,
                "env": deploy_env
            }

        # 获取配置
        conf = get_config('common')
        res = requests.post(urljoin(conf.get('devops_addr'), 'api/devops/deploy/'), json=data)
        msg_list.append(res.json().get('msg'))
    msg_md = "\n".join(msg_list)
    msgs = "# 反馈信息   \n  ---  \n ## 详情  \n%s" % msg_md
    SendMessage.send_md(webhook, msgs)
